<?php

namespace app\index\controller;

use app\api\controller\ApiPrint;
use app\api\controller\JobTask;
use app\common\controller\ActionLogs;
use app\common\controller\Deviceobj;
use app\common\controller\Ekaipiao;
use app\common\controller\Pub;
use app\common\controller\Wxoption;
use app\common\job\SendNotify;
use app\common\model\Agent;
use app\common\model\Bdsy;
use app\common\model\CardConsume;
use app\common\model\CardGeneral;
use app\common\model\CardStatis;
use app\common\model\CardUserGet;
use app\common\model\DevicePrint;
use app\common\model\EfapiaoList;
use app\common\model\Merchant;
use app\common\model\MerchantCashier;
use app\common\model\Mstatis;
use app\common\model\Paylog;
use app\common\model\System;
use app\common\model\WxOpen;
use Csv\Csv;
use Ekaipiao\Epiao;
use feie\HttpClient;
use think\Config;
use think\Controller;
use think\Db;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;
use Weixinpay\Wxtk;
use Weixinpay\Wxtk2;
use Weixinpay\Wxtk3;
use Ylb\Ylb;

class Index extends Controller
{
//    public function test2a(){
//      $path=$_SERVER['DOCUMENT_ROOT'] . "/excel/csv1/";
//      if(!is_dir($path)){
//          $res=mkdir(iconv("UTF-8", "GBK", $path),0777,true);
//          if ($res){
//              echo "目录 $path 创建成功";
//          }else{
//              echo "目录 $path 创建失败";
//          }
//      }
//
//    }
//    public function test1a(){
//        $Merchant=new Merchant();
//        $map['top_mid']=459;
//        $list=$Merchant->where($map)->field('id')->select();
//        foreach($list as $k=>$v){
//            $s[]=$v['id'];
//        }
//
//        $ss=implode(',',$s);
//        $maps['a.mid']=array('in',$ss);
//        $wn_card_consume=new CardConsume();
//        $list2=$wn_card_consume->alias('a')
//            ->join('wn_card_general b','a.card_id=b.card_id','left')
//            ->join('wn_merchant c','a.mid=c.id','left')
//            ->join('wn_card_user_get d','a.openid=d.openid','left')
//            ->where($maps)->field('a.*,b.title as card_title,c.merchant as merchantname,d.nickname,d.name')->select();
//        foreach($list2 as $ks=>$vs){
//            $lists[$ks]['id']=$vs['id'];
//            $lists[$ks]['card_type']=getcardtype($vs['card_type']);
//            $lists[$ks]['card_title']=$vs['card_title'];
//            $lists[$ks]['merchantname']=$vs['merchantname'];
//            $lists[$ks]['nickname']=$vs['nickname'];
//            $lists[$ks]['name']=$vs['name'];
//            $lists[$ks]['code']=$vs['code']."\t";
//            $lists[$ks]['con_username']=$vs['con_username'];
//            $lists[$ks]['source']=$vs['source'];
//            $lists[$ks]['hx_fs']=$vs['hx_fs'];
//            $lists[$ks]['create_time']=$vs['create_time'];
//        }
//        $Csv = new Csv();
//        $header = ['id', '卡券类型', '卡券名称', '门店', '微信昵称', '姓名', '券号', '核销人', '核销渠道', '核销方式', '核销时间']; //表头,名称可自定义
//        $res = $Csv->put_csv($lists, $header);
//        var_dump($res);
//
//    }
    public function testll(){
        $SendNotify=new SendNotify();
        $param['merchantid']=501;
        $param['data']="abcdkskk";

       $ss= $SendNotify->task_biz_notify($param);
    var_dump($ss);
    }
    public function ylb()
    {
        $option = [
            'app_cust_id' => "LETO_ID_Rlo8k25OXe",
            'app_cust_pwd' => "LETO_PWD_yCPreANY1s",
        ];
        $Ylb = new Ylb($option);
        $s = $Ylb->unbind('17764', 'hnwn');
        var_dump($s);
        exit();
        $s = $Ylb->bind('17764', 'hnwn');
//        $s=$Ylb->addvoice('17764',100,8);
//        $s=$Ylb->addvoice('17764',100,11);
////        $s=$Ylb->vol('17764',10);
        var_dump($s);
        $Deviceobj = new Deviceobj();
        $s = $Deviceobj->ylb_sendvoice('H501-20190425181322379644');
        var_dump($s);

    }
    public function testkp(){
        $orderid="H979-20190420090551482484";
        $Ekaipiao=new Ekaipiao();
        $s=$Ekaipiao->send_kp($orderid);
        var_dump($s);
    }

    public function resetfptoken()
    {
        $Epiao = new Epiao();
        $s = $Epiao->token(979);
        halt($s);
    }

    public function testduilie()
    {
        $data = '{"device_id":"315474","paytime":"2018-11-07 10:39:57","merchant":"\u4e5d\u6781\u7f8e\u98df\u57ce","out_trade_no":"dm3026071122","staff":"","total_fee":"0.01","paymode":"\u5fae\u4fe1","bmp":1,"yf_price":"0.01","dis_card_zk":0,"vip_card_zk":0,"gel_card_zk":0,"gel_info":"","client_id":"236042","mid":"755"}';
        $data = json_decode($data, true);
        $JobTask = new JobTask();
        $s = $JobTask->mss_send_wsy_print($data);
        var_dump($s);
    }

    public function piliang()
    {
//        echo  time()+strtotime("+100 year");
//        exit();
        $ps = Request()->param('ps');
        $start = 100 * $ps;
        $CardUserGet = new CardUserGet();
        $map['a.card_type'] = array('neq', "MEMBER_CARD");
        $map['a.type_time'] = "DATE_TYPE_FIX_TIME_RANGE";
        $field = "a.card_id,a.id";
        $list = $CardUserGet->alias('a')->join('wn_card_user_get b', 'a.start_time=b.end_time and a.id = b.id')->field($field)->where($map)->where('a.end_time', 'not null')->limit($start, 1000)->select();
//        var_dump(collection($list)->toArray());
//        exit();
////        $list = $CardUserGet->where($map)->where('end_time', 'not null')->limit($start,3000)->select();
//        $list = $CardUserGet->where($map)->where('end_time', 'not null')->limit($start,3000)->field('start_time,end_time,id')->select();
//        foreach ($list as $k=>$v){
//            if($v['start_time']==$v['end_time']){
//                echo $v['id']."<br />";
//            }
//
//        }
//        exit();

        $data = [];
        foreach ($list as $k => $v) {
            $cardinfo = $this->getaddcardgel($v);
//            var_dump(collection($cardinfo)->toArray());
//            exit();
            if ($cardinfo['time_type'] == 'DATE_TYPE_FIX_TIME_RANGE') {
                $map2['id'] = $v['id'];
                $data['end_time'] = $cardinfo['end_timestamp'];
                $s = $CardUserGet->save($data, $map2);
                var_dump($map2);
                var_dump($data);
                var_dump($s);
            }
//            if ($cardinfo['time_type'] == 'DATE_TYPE_FIX_TERM') {
//
//                $data['end_time'] = $cardinfo['fixed_term'] * 86400 + time();
//            }
//            if ($cardinfo['time_type'] == 'DATE_TYPE_PERMANENT') {
//
//                $data['end_time'] = time() + strtotime("+100 year");
//            }


        }
//        var_dump($cardinfo);
//      echo $list['card_id'];
//      var_dump($list);
//     foreach($list as $k=>$v){
//         $cardinfo = $this->getaddcardgel($data);
//     }


    }

    public function getaddcardgel($param)
    {
        $CardGel = new CardGeneral();
        $cardinfo = $CardGel->where(['card_id' => $param['card_id']])->field('top_mid,mid,time_type,fixed_term,begin_timestamp,end_timestamp')->find();
        if (!$cardinfo) {
            $cardinfo = ['top_mid' => 0, 'mid' => 0];
        }
        return $cardinfo;

    }

    public function testfp()
    {

        $map['id'] = "501";
        $Merchant = new Merchant();
        $Agent = new Agent();
        $System = new System();
        $WxOpen = new WxOpen();
        $user = $Merchant->where($map)->find();
        $config = $Agent->where(array('id' => $user['agent']))->find();
        $users = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
        $usersopen = $WxOpen->where(array('id' => $user['wx_open_id']))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $usersopen['authorizer_appid'],
            'authorizer_refresh_token' => $usersopen['authorizer_refresh_token'],
            // 'partnerkey'=>$agent['partnerkey']
        );
//        var_dump($options);
//        exit();
        $weObj = new Wxobjopen($options);
//
//        $data['contact'] = array(
//            "time_out" => "3600",
//            "phone" => "18568816812",
//
//        );
////
////        exit();
////
///
//        $at = $weObj->setcontactinfo($data);
//        var_dump($at);
//        exit();
//        exit();
//        $at=$weObj->get_authorizer_access_token();
//        $at=$weObj->getcontactinfo();
//        $data['paymch_info'] = array(
//            'mchid' => "1389929902",
//            's_pappid' => "d3gwNDY3YTJhZWRiNzRjMzE3XylUwBi3ze4ID72FVSAHv3akR7IK6_n5WPwp2II_NUTq",
//
//        );
//        $at = $weObj->setpaymch($data);
//        var_dump($at);
//        exit();

//        var_dump(json_encode($data));
//        $at=$weObj->getpaymch();
//        var_dump($at);
//        exit();
        $sinfo = '{"ToUserName":"gh_7cce5f015893","FromUserName":"oCVCLv4uiIZlnKFPbMPRWJBlXdgo","CreateTime":"1545149336","MsgType":"event","Event":"user_authorize_invoice","SuccOrderId":"H501-2018121900082619466","FailOrderId":{},"AuthorizeAppId":"wx26dd3a738e5b357c","Source":"pay","SPAppId":"d3gwNDY3YTJhZWRiNzRjMzE3XylUwBi3ze4ID72FVSAHv3akR7IK6_n5WPwp2II_NUTq"}';
        $sinfo = json_decode($sinfo, true);
        $Ekaipiao = new Ekaipiao();
        $a = $Ekaipiao->save_fp($sinfo);
        var_dump($a);
        exit();
//var_dump($authdata);
        exit();
        $data['wxopenid'] = "oCVCLv4uiIZlnKFPbMPRWJBlXdgo";// String	是	用户的openid 用户知道是谁在开票
        $data['ddh'] = "H501-2018121517401176094";    //String	是	订单号，企业自己内部的订单号码。注1
        $data['fpqqlsh'] = "1485786252201812151046366";    //String	是	发票请求流水号，唯一识别开票请求的流水号。注2
        $data['nsrsbh'] = "914105810969390037";    //String	是	纳税人识别码
        $data['nsrmc'] = "河南悟能网络科技有限公司";    //String	是	纳税人名称
        $data['nsrdz'] = "河南省林州市红旗渠大道国家863红旗渠科技产业园1号楼";    //String	是	纳税人地址
        $data['nsrdh'] = "18568816812";    //String	是	纳税人电话
        $data['nsrbank'] = "中国工商银行股份有限公司林州清华苑支行";    //String	是	纳税人开户行
        $data['nsrbankid'] = "1706922009100000516";    //String	是	纳税人银行账号
        $data['ghfmc'] = "李世正";    //Sring	是	购货方名称
//        $data['ghfnsrsbh'] = "";    //String	否	购货方识别号
//        $data['ghfdz'] = "";    //String	否	购货方地址
//        $data['ghfdh'] = "";    //String	否	购货方电话
//        $data['ghfbank'] = "";    //String	否	购货方开户行
//        $data['ghfbankid'] = "";    //String	否	购货方银行帐号
        $data['kpr'] = "test";    //String	是	开票人
//        $data['skr'] = "";    //String	否	收款人
//        $data['fhr'] = "";    //String	否	复核人
        $data['jshj'] = 1;    //String	是	价税合计
        $data['hjse'] = 0.03;    //String	是	合计税额
        $data['hjje'] = 0.97;    //String	是   合计金额
        $data['bz'] = "H571-201812151046366";    //String	否	备注
        $data['hylx'] = "1";    //String	否	行业类型 0 商业 1其它
        $data['invoicedetail_list'] = array(array(
            'fphxz' => "0",//String	是	发票行性质 0 正常 1折扣 2 被折扣
            'spbm' => "1090510030000000000",//String	是	19位税收分类编码说明见注
            'xmmc' => "*计算机网络设备*路由器",//String	是	项目名称
//            'dw'=>"",//String	否	计量单位
//            'ggxh'=>"",//String	否	规格型号
            'xmsl' => 1,//String	是	项目数量
            'xmdj' => 1,//String	是	项目单价
            'xmje' => 0.97,//String	是	项目金额 不含税，单位元 两位小数
            'sl' => 0.03,//String	是	税率 精确到两位小数 如0.01
            'se' => "0",//String	是	税额 单位元 两位小数
        ));    //List	是	发票行项目数据
        $se_param['invoiceinfo'] = $data;
        var_dump(json_encode($se_param, JSON_UNESCAPED_UNICODE));
        $at = $weObj->makeoutinvoice($se_param);

        var_dump($at);

    }

    public function testekaipiao()
    {

        $Epiao = new Epiao();

//        $data=array(
//             "company"=>"河南悟能网络科技有限公司",
//             "invoice"=>"914105810969390037",
//             "kpjh"=>"499916257477",
//             "address"=>"河南省林州市红旗渠大道国家863红旗渠科技产业园1号楼4楼",
//             "tel"=>"18568816812",
//             "contact"=>"李世正",
//        );
//        $at=$Epiao->register($data);
//        var_dump($at);
//        exit();
////
//
        $data = array(
//            "company"=>"河南悟能网络科技有限公司",
            "invoice" => "914105810969390037",
            "kpjh" => "499916257477",
//            "address"=>"河南省林州市红旗渠大道国家863红旗渠科技产业园1号楼4楼",
//            "tel"=>"18568816812",
//            "contact"=>"李世正",
        );
        $at = $Epiao->token(501);

        $fpmm_info = array(
            'group' => array(
                'spmc' => '*计算机网络设备*网络连接设备',//商品名称2
                'ggxh' => '',//规格型号
                'jldw' => '',//单位
                'spsl' => '1',//00000000商品数量
                'spdj' => '0.01',//00000000单价
                'je' => '1',//0.50金额
                'slv' => '0.05',//0.17税率
                'se' => '0.95',//1.50税额
                'hsbz' => '1',//0含税标志 0 不含税 1 含税
                'spbm' => '1090510030000000000',//0含税标志 0 不含税 1 含税
                'SYYHZCBZ' => '0',//是否有优惠政策(0没有1有)
                'YHZCSM' => '',//优惠政策内容
            ),
//            'group2' => array(
//                'spmc' => '',//商品名称2
//                'ggxh' => '',//规格型号
//                'jldw' => '',//单位
//                'spsl' => '',//00000000商品数量
//                'spdj' => '',//00000000单价
//                'je' => '',//0.50金额
//                'slv' => '',//0.17税率
//                'se' => '',//1.50税额
//                'hsbz' => '',//0含税标志 0 不含税 1 含税
//                'SYYHZCBZ' => '',//是否有优惠政策(0没有1有)
//                'YHZCSM' => '',//优惠政策内容
//            ),
        );

        $kpxx_arr = array(
            'gfmc' => "李世正",//购方名称
            'sh' => "",//税号
            'yhzh' => "",//银行账号
            'dzdh' => "",//地址电话
            'email' => "",//邮箱
            'fpzl' => "t",//发票种类s专票 c普票 t 电子发票
            'bz' => "test" . rand(100, 999),//备注
        );

        $doc = new \DOMDocument('1.0', 'utf-8');
        $doc->formatOutput = true;//格式化输出格式
        $business = $doc->createElement('business');//创建一个标签
        $body = $doc->createElement('body');//创建一个标签
        $input = $doc->createElement('input');//创建一个标签
        $kpxx = $doc->createElement('kpxx');//创建一个标签
        $fpmx = $doc->createElement('fpmx');//创建一个标签
        //开票信息内容
        foreach ($kpxx_arr as $k => $v) {
            $a[$k] = $doc->createElement($k);
            $a[$k]->appendChild($doc->createTextNode($v));
            $kpxx->appendChild($a[$k]);
            $input->appendChild($kpxx);
        }
        $fpmx_info = $doc->createTextNode(count($fpmm_info));//设置属性内容
        $fpmx_id = $doc->createAttribute('count');//设置属性
        $fpmx_id->appendChild($fpmx_info);//将属性内容赋给属性
        $fpmx->appendChild($fpmx_id);
        $i = 1;
        foreach ($fpmm_info as $ks => $vs) {
            $group[$ks] = $doc->createElement('group');
            foreach ($vs as $ka => $va) {

                $group_info[$ks] = $doc->createTextNode($i);//设置属性内容
                $group_id[$ks] = $doc->createAttribute('xh');//设置属性
                $group_id[$ks]->appendChild($group_info[$ks]);//将属性内容赋给属性
                $group[$ks]->appendChild($group_id[$ks]);

                $b[$ka] = $doc->createElement($ka);
                $b[$ka]->appendChild($doc->createTextNode($va));
                $group[$ks]->appendChild($b[$ka]);
                $fpmx->appendChild($group[$ks]);

            }
            $i++;

            $input->appendChild($fpmx);

        }
        //开票信息内容结束

//        $newso = $doc->createTextNode('33333333');//设置标签内容
        $business_info = $doc->createTextNode("zzsfp");//设置属性内容
        $business_id = $doc->createAttribute('id');//设置属性
        $business_id->appendChild($business_info);//将属性内容赋给属性
        $business_info2 = $doc->createTextNode("H501-2018121517475274434");//设置属性内容
        $business_id2 = $doc->createAttribute('comment');//设置属性
        $business_id2->appendChild($business_info2);//将属性内容赋给属性（订单号）
//        $body->appendChild($newso);//将标签内容赋给标签】
        $input->appendChild($kpxx);
        $body_info = $doc->createTextNode("1");//设置属性内容
        $body_id = $doc->createAttribute('yylxdm');//设置属性
        $body_id->appendChild($body_info);//将属性内容赋给属性
        $body->appendChild($body_id);
        $body->appendChild($input);

        $business->appendChild($business_id);//将属性赋给标签
        $business->appendChild($business_id2);//将属性赋给标签
        $business->appendChild($body);


        $doc->appendChild($business);
        $xml = $doc->saveXML();
//       echo $xml;
        $data = array(
            'invoice' => "914105810969390037",
            'kpjh' => "499916257477",
            'token' => "UosJ3496AOv/1/TV+TEiKtYSZurFK2jl1HxdHF4Sxm/4HIIuAWW8y+Mg/B75qJb4",
            'xml' => $xml,
            'appid' => "wx26dd3a738e5b357c",
            'orderId' => "H501-2018121819263528429",
            'os_type' => "Linux",

        );
        $at = $Epiao->kaipiao($data);
        var_dump($at);


    }

    public function testab()
    {
        $str = "respDesc=%E6%88%90%E5%8A%9F&jsonData=%7B%22reqSerialNum%22%3A%22wx_config-201810181628169093%22%2C%22businessStat%22%3A%22S%22%2C%22pnrpayMessage%22%3A%22%7B%5C%22appid%5C%22%3A%5C%22SUCCESS%5C%22%2C%5C%22path%5C%22%3A%5C%22SUCCESS%5C%22%2C%5C%22subscribeAppid%5C%22%3A%5C%22SUCCESS%5C%22%7D%22%2C%22memberId%22%3A%22310000016000065151%22%7D&checkValue=04846c7bfb626505736c03d92fb0b38c28bf27f1f3312855c235338691605d10&respCode=000000";
        $urlde_data = urldecode($str);
        $urlde_data = explode('&', $urlde_data);
        $urlde_data = explode('=', $urlde_data[1]);
        $data = json_decode($urlde_data[1], true);

        var_dump($data);

    }
    public function testabccard(){

        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $Merchant=new Merchant();
        $map['id']="1154";
        $mchinfo=$Merchant->where($map)->find();
        $config = $Agent->where(array('id' => $mchinfo['agent']))->find();
        $users = $WxOpen->where(array('id' => $mchinfo['wx_open_id']))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],

        );

        $WeObj = new Wxobjopen($options);
        $params['openid'] = "oQtYbv-IeFbCltw-rU_N-ZTityDg";
//        $params['card_id'] = "pQtYbv2qBMK38QlpvJJzkcm8vX0w";
        $img = $WeObj->userGetCard($params);
        var_dump($img);

    }

    public function createqrcode()
    {

        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $config = $Agent->where(array('id' => 15))->find();
        $users = $WxOpen->where(array('id' => 20))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],

        );

        $WeObj = new Wxobjopen($options);
        $sence_id = "123456";
        $img = $WeObj->getQRCode($sence_id, 0);
        var_dump($img);

    }

    public function testtest()
    {
        $postStr = "";
        $payinfo = Paylog::where('id', 161360)->find();
        $Pub = new Pub();

        $Pub->sendnotify($payinfo['mid'], $postStr);
//        $ActionLogs = new ActionLogs();
//        $alldata['acids'] = "3kfjakljfklajsfjsl";
//        $s = $ActionLogs->writelog("payos", "wxauth122", "event", $alldata, "wx:");
//        var_dump($s);

    }

    private function getprintid($mid)
    {

        $map['id'] = $mid;
        $name = Merchant::where($map)->value('agent');
        $agentinfo = Agent::where('id', $name)->find();
        $param['appid'] = $agentinfo['wsy_print_appid'];
        $param['key'] = $agentinfo['wsy_print_key'];
        return $param;

    }

    public function testabc()
    {
        $s = $this->getprintid('501');
        $client_id = "248219";
        $device_id = "329745";
        $appid = $s['appid'];
        $key = $s['key'];
        $ApiPrint = new ApiPrint();
        $keys = $ApiPrint->getparam($client_id, $device_id, $appid, $key);
        var_dump($keys);
//        $info = $ApiPrint->wsyprint($paramd, $keys);
    }

    public function testcardstatis()
    {
        for ($i = 21; $i >= 1; $i--) {
            $start_time = strtotime(date('Y-m-d')) - 86400 * $i;
            $end_time = $start_time + 86399;
//            var_dump($start_time);
//            halt($end_time);
//        $start_time=1536076800;
//        $end_time=$start_time+86399;
            //领卡统计
            $condition_1 = "b.mid = a.id and b.card_type='MEMBER_CARD' and (b.create_time >= :start_time and b.create_time <= :end_time)";
            $param = ['start_time' => $start_time, 'end_time' => $end_time];
            $field = 'a.id as mid,a.top_mid,a.agent,a.id,count(b.id) as rec_card_num';
            $rec_card_data = $this->getcardstatis($condition_1, $param, $field);
            //退卡统计
            $condition_2 = "b.mid = a.id and b.card_type='MEMBER_CARD' and have =0 and (b.del_time >= :start_time and b.del_time <= :end_time)";
            $param = ['start_time' => $start_time, 'end_time' => $end_time];
            $field = 'a.id as mid,a.top_mid,a.agent,a.id,count(b.id) as ret_card_num';
            $ret_card_data = $this->getcardstatis($condition_2, $param, $field);
//        //实充消费 赠送统计
            $condition = "b.mid = a.id and cate=:cate and pay_cate=:pay_cate and type=1 and (b.create_time >= :start_time and b.create_time <= :end_time)";

            //微信实充金额
            $param = ['start_time' => $start_time, 'end_time' => $end_time, 'cate' => 1, 'pay_cate' => 2];
            $field = 'a.id as mid,a.top_mid,a.agent,a.id,sum(b.num) as wx_rec_fee';
            $wx_rec_data = $this->getcardfeestatis($condition, $param, $field);
            //微信赠送金额
            $param = ['start_time' => $start_time, 'end_time' => $end_time, 'cate' => 3, 'pay_cate' => 2];
            $field = 'a.id as mid,a.top_mid,a.agent,a.id,sum(b.num) as wx_give_fee';
            $wx_give_data = $this->getcardfeestatis($condition, $param, $field);
            //微信自助实充金额
            $param = ['start_time' => $start_time, 'end_time' => $end_time, 'cate' => 1, 'pay_cate' => 0];
            $field = 'a.id as mid,a.top_mid,a.agent,a.id,sum(b.num) as wxonline_rec_fee';
            $wxonline_rec_data = $this->getcardfeestatis($condition, $param, $field);
            //微信自助赠送金额
            $param = ['start_time' => $start_time, 'end_time' => $end_time, 'cate' => 3, 'pay_cate' => 0];
            $field = 'a.id as mid,a.top_mid,a.agent,a.id,sum(b.num) as wxonline_give_fee';
            $wxonline_give_data = $this->getcardfeestatis($condition, $param, $field);
            //支付宝实充金额
            $param = ['start_time' => $start_time, 'end_time' => $end_time, 'cate' => 1, 'pay_cate' => 1];
            $field = 'a.id as mid,a.top_mid,a.agent,a.id,sum(b.num) as ali_rec_fee';
            $ali_rec_data = $this->getcardfeestatis($condition, $param, $field);
            //支付宝赠送
            $param = ['start_time' => $start_time, 'end_time' => $end_time, 'cate' => 3, 'pay_cate' => 1];
            $field = 'a.id as mid,a.top_mid,a.agent,a.id,sum(b.num) as ali_give_fee';
            $ali_give_data = $this->getcardfeestatis($condition, $param, $field);
            //支付宝自助充值金额
            $param = ['start_time' => $start_time, 'end_time' => $end_time, 'cate' => 1, 'pay_cate' => 3];
            $field = 'a.id as mid,a.top_mid,a.agent,a.id,sum(b.num) as alionline_rec_fee';
            $alionline_rec_data = $this->getcardfeestatis($condition, $param, $field);
            //支付宝自助赠送
            $param = ['start_time' => $start_time, 'end_time' => $end_time, 'cate' => 3, 'pay_cate' => 3];
            $field = 'a.id as mid,a.top_mid,a.agent,a.id,sum(b.num) as alionline_give_fee';
            $alionline_give_data = $this->getcardfeestatis($condition, $param, $field);
            //现金实充金额
            $param = ['start_time' => $start_time, 'end_time' => $end_time, 'cate' => 1, 'pay_cate' => 4];
            $field = 'a.id as mid,a.top_mid,a.agent,a.id,sum(b.num) as cash_rec_fee';
            $cash_rec_data = $this->getcardfeestatis($condition, $param, $field);
            //现金充值赠送金额
            $param = ['start_time' => $start_time, 'end_time' => $end_time, 'cate' => 3, 'pay_cate' => 4];
            $field = 'a.id as mid,a.top_mid,a.agent,a.id,sum(b.num) as cash_give_fee';
            $cash_give_data = $this->getcardfeestatis($condition, $param, $field);

            $condition_z = "b.mid = a.id and cate=:cate and pay_cate in (0,1,2,3,4) and type=1 and (b.create_time >= :start_time and b.create_time <= :end_time)";
            //总计充值金额
            $param = ['start_time' => $start_time, 'end_time' => $end_time, 'cate' => 1];
            $field = 'a.id as mid,a.top_mid,a.agent,a.id,sum(b.num) as rec_fee';
            $rec_data = $this->getcardfeestatis($condition_z, $param, $field);
            //总计赠送金额
            $param = ['start_time' => $start_time, 'end_time' => $end_time, 'cate' => 3];
            $field = 'a.id as mid,a.top_mid,a.agent,a.id,sum(b.num) as give_fee';
            $give_data = $this->getcardfeestatis($condition_z, $param, $field);


            //会员卡消费金额&次数
            $condition_con = "b.mid = a.id and type=2 and cate=2 and (b.create_time >= :start_time and b.create_time <= :end_time)";

            $param = ['start_time' => $start_time, 'end_time' => $end_time];
            $field = 'a.id as mid,a.top_mid,a.agent,a.id,sum(b.num) as con_fee,count(b.id) as con_order';
            $con_data = $this->getcardfeestatis($condition_con, $param, $field);
            //会员卡赠送积分
            $condition_bonus = "b.mid = a.id and type=1 and cate not in(2,9) and (b.create_time >= :start_time and b.create_time <= :end_time)";
            $field = 'a.id as mid,a.top_mid,a.agent,a.id,sum(b.num) as give_bonus';
            $param = ['start_time' => $start_time, 'end_time' => $end_time];
            $rec_bonus_data = $this->getcardbonusstatis($condition_bonus, $param, $field);
            $condition_bonus = "b.mid = a.id and type=2 and cate in(2,9) and (b.create_time >= :start_time and b.create_time <= :end_time)";
            $field = 'a.id as mid,a.top_mid,a.agent,a.id,sum(b.num) as con_bonus';
            $param = ['start_time' => $start_time, 'end_time' => $end_time];
            $con_bonus_data = $this->getcardbonusstatis($condition_bonus, $param, $field);
            $infos = array_merge($rec_card_data, $ret_card_data, $wx_rec_data, $wx_give_data, $wxonline_rec_data, $wxonline_give_data,
                $ali_rec_data, $ali_give_data, $alionline_rec_data, $alionline_give_data,
                $cash_rec_data, $cash_give_data, $rec_data, $give_data, $con_data, $rec_bonus_data, $con_bonus_data
            );
            $mchlist = array_unique(array_column($rec_data, 'mid'));
            foreach ($mchlist as $k => $v) {
                foreach ($infos as $ks => $vs) {
                    if ($vs['mid'] == $v) {
                        $infos2[$k]['mid'] = $vs['mid'];
                        $infos2[$k]['agent'] = $vs['agent'];
                        $infos2[$k]['top_mid'] = $vs['top_mid'];
                        $infos2[$k]['create_time'] = time();
                        $infos2[$k]['statis_time'] = date('Y-m-d H:i:s', $start_time);
                        $infos2[$k]['statis_times'] = $start_time;
                        $infos2[$k]['statis_action'] = 1;
                        $infos2[$k]['month'] = date('Y-m', $start_time);
                        if (array_key_exists('rec_card_num', $vs)) {
                            $infos2[$k]['rec_card_num'] = number_format($vs['rec_card_num'], 2);
                        }
                        if (array_key_exists('ret_card_num', $vs)) {
                            $infos2[$k]['ret_card_num'] = number_format($vs['ret_card_num'], 2);
                        }
                        if (array_key_exists('wx_rec_fee', $vs)) {
                            $infos2[$k]['wx_rec_fee'] = number_format($vs['wx_rec_fee'], 2);
                        }
                        if (array_key_exists('wx_give_fee', $vs)) {
                            $infos2[$k]['wx_give_fee'] = number_format($vs['wx_give_fee'], 2);
                        }
                        if (array_key_exists('wxonline_rec_fee', $vs)) {
                            $infos2[$k]['wxonline_rec_fee'] = number_format($vs['wxonline_rec_fee'], 2);
                        }
                        if (array_key_exists('wxonline_give_fee', $vs)) {
                            $infos2[$k]['wxonline_give_fee'] = number_format($vs['wxonline_give_fee'], 2);
                        }
                        if (array_key_exists('ali_rec_fee', $vs)) {
                            $infos2[$k]['ali_rec_fee'] = number_format($vs['ali_rec_fee'], 2);
                        }
                        if (array_key_exists('ali_give_fee', $vs)) {
                            $infos2[$k]['ali_give_fee'] = number_format($vs['ali_give_fee'], 2);
                        }
                        if (array_key_exists('alionline_give_fee', $vs)) {
                            $infos2[$k]['alionline_give_fee'] = number_format($vs['alionline_give_fee'], 2);
                        }
                        if (array_key_exists('alionline_rec_fee', $vs)) {
                            $infos2[$k]['alionline_rec_fee'] = number_format($vs['alionline_rec_fee'], 2);
                        }
                        if (array_key_exists('cash_rec_fee', $vs)) {
                            $infos2[$k]['cash_rec_fee'] = number_format($vs['cash_rec_fee'], 2);
                        }
                        if (array_key_exists('cash_give_fee', $vs)) {
                            $infos2[$k]['cash_give_fee'] = number_format($vs['cash_give_fee'], 2);
                        }
                        if (array_key_exists('rec_fee', $vs)) {
                            $infos2[$k]['rec_fee'] = number_format($vs['rec_fee'], 2);
                        }
                        if (array_key_exists('give_fee', $vs)) {
                            $infos2[$k]['give_fee'] = number_format($vs['give_fee'], 2);
                        }
                        if (array_key_exists('con_fee', $vs)) {
                            $infos2[$k]['con_fee'] = number_format($vs['con_fee'], 2);
                        }
                        if (array_key_exists('give_bonus', $vs)) {
                            $infos2[$k]['give_bonus'] = $vs['give_bonus'];
                        }
                        if (array_key_exists('con_order', $vs)) {
                            $infos2[$k]['con_order'] = $vs['con_order'];
                        }
                        if (array_key_exists('con_bonus', $vs)) {
                            $infos2[$k]['con_bonus'] = $vs['con_bonus'];
                        }
                    }


                }

            }
            $MchStatis = new CardStatis();
            $MchStatis->saveAll($infos2);
        }
        var_dump($infos2);
    }

    private function getcardstatis($condition, $param, $field)
    {
        $Merchant = new Merchant();

        $sql = $Merchant
            ->alias('a')
            ->join('wn_card_user_get b', $condition, "LEFT")
            ->group('a.id')
            ->bind($param)
            ->field($field)
            ->select();

//        return $sql;

        return collection($sql)->toArray();

    }

    private function getcardfeestatis($condition, $param, $field)
    {
        $Merchant = new Merchant();

        $sql = $Merchant
            ->alias('a')
            ->join('wn_card_user_fee b', $condition, "LEFT")
            ->group('a.id')
            ->bind($param)
            ->field($field)
            ->select();

//        return $sql;

        return collection($sql)->toArray();

    }

    private function getcardbonusstatis($condition, $param, $field)
    {
        $Merchant = new Merchant();

        $sql = $Merchant
            ->alias('a')
            ->join('wn_card_user_bonus b', $condition, "LEFT")
            ->group('a.id')
            ->bind($param)
            ->field($field)
            ->select();

//        return $sql;

        return collection($sql)->toArray();

    }

    public function testsendde()
    {

    }


    public function testsign()
    {

        $data['merchid'] = 501;
        $data['auth_code'] = "135291641887503806";
        $data['client_ip'] = "admin";
        $data['cashier'] = "admin";
        $data['confirm'] = "yes";
        $data['price'] = "0.01";
        $data['type'] = "pay";
        $data['appid'] = "20180501";
        $data['sign'] = MD5('appid=20180501&auth_code=135291641887503806&cashier=admin&client_ip=admin&confirm=yes&merchid=501&price=0.01&type=pay83d96c2aec5deaa8e2d675d9121cef4e1');
        $s = checksj($data, "MD5");
        var_dump($s);

    }

    public function tests()
    {
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $Merchant = new Merchant();
        $config = $Agent->where(array('id' => 28))->find();
//        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
//            'authorizer_appid' =>1,
//            'authorizer_refresh_token' => 2,
        );
        var_dump($options);
        $Weobj = new Wxobjopen($options);
        $s = $Weobj->checkopenAuth();
        var_dump($s);

    }

    public function tktest()
    {

        $map['id'] = 501;
        $data['orderid'] = "H501-2018041216003868068";
        $data['price'] = "0.3";
        $data['refund_fee'] = "0.3";
        $data['merchid'] = "501";
        $data['refund_desc'] = "test";
        $User = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $Patlog = new Paylog();
        $config = $User->where($map)->find();
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
        $order = $Patlog->where('orderid', $data['orderid'])->find();
        $options['wx_open_id'] = $agent['wx_open_id'];
        $weObj = new Wxtk3($options);
        $tk_orderid = $this->getorder($data['merchid']);
        $notice = $weObj->generateNonceStr();
        $weObj->setParameter('appid', $users['authorizer_appid']);
        $weObj->setParameter('mch_id', $agent['partnerid']);
        $weObj->setParameter('sub_mch_id', $config['sub_mch_id']);
        $weObj->setParameter('nonce_str', $notice);
        $weObj->setParameter('refund_desc', isset($data['refund_desc']) ? $data['refund_desc'] : 0);
        $weObj->setParameter('out_trade_no', $data['orderid']);
        $weObj->setParameter('out_refund_no', $tk_orderid);
        $weObj->setParameter('total_fee', $order['price'] * 100);
        $weObj->setParameter('refund_fee', $data['refund_fee'] * 100);
        $sss = $weObj->create_refund_xml($agent['partnerkey']);
        $url = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
        $responseXml = $weObj->curl_post_ssl($url, $sss);

        $responseObj = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
        var_dump($responseObj);

    }



    public function test2()
    {
        $paylog = new Paylog();
        $Merchant = new Merchant();
        $Mstatis = new Mstatis();
        $machlist = $Merchant->field('id,merchant,addtime')->order('id asc')->select();
        $data = [];
//    $day = strtotime(date('Y-m-d', strtotime('-1 day')));
//    $day2 = $day-(86400*0) + 86399;
//    echo date('Y-m-d H:i:s',$day);
//    echo date('Y-m-d H:i:s',$day2);
//    exit();
        $day = strtotime(date('Y-m-d', strtotime('-7 day')));
        $day2 = $day + 86399;
        echo date('Y-m-d H:i:s', $day);
        echo date('Y-m-d H:i:s', $day2);
        exit();
        foreach ($machlist as $k => $v) {
//     echo $v['id'];
//     echo "<br />";

//    echo date('Y-m-d H:i:s',$day);
//    echo date('Y-m-d H:i:s',$day2);
//    exit();
            $where['dtime'] = $day;
            $where['mid'] = $v['id'];
            $where['fs'] = 'day';
            $cx = $Mstatis->where($where)->count();

            if ($cx == 0) {
                $map['mid'] = $v['id'];
                $map['add_time'] = array('between', '' . $day . ',' . $day2 . '');
                $map['pay_statu'] = array(array('neq', 0), array('neq', 8), 'and');
                $jorder = $paylog->where($map)->count();
                $mae = $map;
                $mae['tk_price'] = array('neq', 0.00);
                $torder = $paylog->where($mae)->count();
                $data['orders'] = $jorder - $torder;
                $jprice = $paylog->where($map)->sum('price');
                $tprice = $paylog->where($map)->sum('tk_price');
                $price = @($jprice - $tprice);
                $data['price'] = isset($price) ? $price : 0;
                $data['mach'] = $paylog->where($map)->count('distinct(mid)');
                $data['mid'] = $v['id'];
                $data['merchant'] = $v['merchant'];
                $data['dtime'] = $day;
                $data['addtime'] = date('Y-m-d H:i:s', $day2);
                $data['tk_price'] = $tprice;
                $data['tk_order'] = $torder;
                $data['fs'] = 'day';
                $Mstatis->allowField(true)->save($data);
            }
        }
//    $Mstatis->allowField(true)->saveAll($data);
//    echo $Mstatis->getLastSql();
    }


    public function test()
    {

//        $data['type'] = "payrefund";
//        $data['merchid'] = 501;
//        $data['username'] = "lsz";
//        $data['tk_pass'] = "123456";
//        $data['orderid'] = "H501-20171229115214890337";
//        $data['device_code'] = "d9a19b6f75d21e0a6bffa373e49b67aa";
//        $data['refund_fee'] = 1;
//        $data['refund_desc'] = 1;
//        $data2['type'] = "card_cz_list";
//        $data2['merchid'] = "523";
        $res = action('api/api/test');
        var_dump($res);
    }

    public function order_query($orderid)
    {
        $Paylog = new Paylog();
        $mab['orderid'] = $orderid;
        $id = $Paylog->where($mab)->find();
        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $map['id'] = $id['mid'];
        $config = $Merchant->where($map)->find();
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
        $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();

        $options = array(
            'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
            'partnerid' => $agent['partnerid'], // 财付通商户身份标识
            'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
        );

        $weObj = new Wxobjopen($options);
        $appid = $users['authorizer_appid'];
        $mch_id = $agent['partnerid'];
        $out_trade_no = $orderid;
        $nonce_str = $weObj->generateNonceStr();
        $sub_mch_id = $config['sub_mch_id'];
        $sub_appid = $userwx['authorizer_appid'];
        $pay_xml = $weObj->createOrderXml($appid, $mch_id, $sub_appid, $sub_mch_id, $out_trade_no, $nonce_str);
        $payorder_xml = $weObj->getPayNum($pay_xml);
        $orderno = $payorder_xml['transaction_id'];
        $pay_zt = $payorder_xml['trade_state'];
        if ($pay_zt == "SUCCESS") {
            $Paylog = new Paylog();
            $data['pay_statu'] = 1;
            $data['orderno'] = $orderno;
            $data['ser_openid'] = $payorder_xml['openid'];
            $data['pay_time'] = $payorder_xml['time_end'];
            $data['payinfo'] = json_encode($payorder_xml, true);

            $data['sub_openid'] = $payorder_xml['sub_openid'];
            $Paylog->save($data, ['orderid' => $payorder_xml['out_trade_no']]);
            $id = $Paylog->where(['orderid' => $payorder_xml['out_trade_no']])->find();
            if ($id['tzzt'] == '0') {
                $s = action('Wxauth/sendtemplate', array($id['mid'], $orderid));
                action('Index/sendprint', array($id));
                $da['tzzt'] = 1;
                $da['tzmsg'] = json_encode($s);
                if ($id['attach'] == "cardcz") {
                    $updata['mid'] = $id['mid'];
                    $updata['openid'] = $id['openid'];
                    $updata['price'] = $id['price'];
                    $updata['orderid'] = $id['orderid'];
                    $updata['get_card_id'] = $id['cz_card_id'];
                    $this->updata_card_info($updata);
                }
                if ($id['attach'] == "qrcodezf") {
                    $inc_bonus['mid'] = $id['mid'];
                    $inc_bonus['openid'] = $id['sub_openid'];
                    $inc_bonus['price'] = $id['price'];
                    $this->inc_bonus($inc_bonus);
                    //增加积分END
                    if (json_decode($id['hx_card'], true) <> '0000') {
                        $hxdata['openid'] = $id['sub_openid'];
                        $hxdata['merchid'] = $id['mid'];
                        $hxdata['cashier'] = $id['cashier'];
                        $hxdata['orderid'] = $id['orderid'];
                        $this->pay_hx_card(json_decode($id['hx_card'], true), $hxdata);
                    }

                }
                $Paylog->save($da, ['orderid' => $payorder_xml['out_trade_no']]);
            }
        }
    }

    public function updata_card_info($updata)
    {
        $CardUserGet = new CardUserGet();
        $CardUserUpdate = new CardUserUpdate();
        $CardCzLog = new CardCzLog();
        //查询领卡记录
        $cardinfo = $CardUserGet->where('id', $updata['get_card_id'])->find();
        //余额更新
        $arr['card_id'] = $cardinfo['card_id'];
        $arr['code'] = $cardinfo['code'];
        $arr['openid'] = $updata['openid'];
        $arr['mid'] = $updata['mid'];
        //赠送金额
        $zsprice = $CardCzLog->where('orderid', $updata['orderid'])->value('zs_price');
        if ($zsprice) {
            $arr['add_balance'] = $updata['price'] + $zsprice;
        } else {
            $arr['add_balance'] = $updata['price'];
        }
        $CardUserGet->where('id', $updata['get_card_id'])->setInc('balance', $arr['add_balance']);
        //余额变动模版消息
        $data_tpl['openid'] = $arr['openid'];
        $data_tpl['balance'] = $CardUserGet->where(array('card_id' => $arr['card_id'], 'code' => $arr['code']))->value('balance');
        $data_tpl['card_id'] = $arr['card_id'];
        $data_tpl['add_balance'] = $arr['add_balance'];
        $data_tpl['type'] = 1;
        $resu['balance'] = $this->tpl_cz_mesg($data_tpl);       //模版消息结果

        //积分变动
        $CardMember = new CardMember();
        $card = $CardMember->where('card_id', $cardinfo['card_id'])->find();
        if ($card['supply_bonus'] == 1) {
            $giveid = $CardCzLog->where('orderid', $updata['orderid'])->value('giveid');    //获取该笔订单规则ID
            if ($giveid > 0) {                                                                               //充值规则
                $bonusarr['orderid'] = $updata['orderid'];                  //订单编号
                $bonusarr['code'] = $cardinfo['code'];                       //会员卡code
                $bonusarr['card_id'] = $cardinfo['card_id'];                //会员卡card_id
                $bonusarr['get_card_id'] = $cardinfo['id'];                 //领取id
                //冲送积分
                $resut['bonus'] = $this->cs_bonus($bonusarr);                //赠送积分
            } else {                                                                                        //无充值规则
                //设置积分
                $bonus_rule = json_decode($card['bonus_rule'], true);
                //比例和积分
                $bili = @($bonus_rule['increase_bonus'] / $bonus_rule['cost_money_unit']);
                $add_bonus = floor($arr['add_balance'] * $bili);
                //同步微信数据
                $bonus['code'] = $cardinfo['code'];
                $bonus['card_id'] = $cardinfo['card_id'];
                $bonus['record_bonus'] = '充值赠送';
                $bonus['add_bonus'] = $add_bonus;
                $resu['bonus'] = $this->bonusgive($bonus);        //积分结果
                if ($resu['bonus']['errcode'] == 0) {
                    $datas['add_bonus'] = $add_bonus;
                    $datas['record_bonus'] = '充值赠送';
                }
            }
        }

        //充值送券模版消息
        $cardarr['orderid'] = $updata['orderid'];
        $cardarr['openid'] = $cardinfo['openid'];
        $cardarr['nickname'] = $cardinfo['nickname'];
        $resut['card'] = $this->cs_card($cardarr);   //赠送卡券结果
        //记录更新
        $datas['mid'] = $arr['mid'];                        //mid
        $datas['openid'] = $cardinfo['openid'];             //openid
        $datas['code'] = $cardinfo['code'];                 //code
        $datas['card_id'] = $cardinfo['card_id'];           //card_id
        $datas['create_time'] = time();                     //时间
        $datas['outerid'] = $arr['mid'];                    //来源
        $datas['add_balance'] = $arr['add_balance'];        //增加金额
        $datas['pay_balance'] = $updata['price'];           //支付金额
        $datas['type'] = 1;                                   //类别
        $datas['hx_fs'] = 8;
        $datas['cate'] = 2;
        $datas['reason'] = 3;
        $datas['source'] = 2;
        $datas['record_balance'] = '在线充值';              //在线充值
        $datas['tplmesg_info'] = json_encode($resu);        //模版消息结果
        $datas['tplmesg_info_zs'] = json_encode($resut);    //赠送模版消息结果
//        $datas['hx_fs'] = '在线充值';                       //
        $datas['con_username'] = 'ONLINERECH';

        $CardUserUpdate->allowField(true)->save($datas);        //保存记录

    }

    public function order_querys()
    {
        $orderid = "H523-2018031518385271433";
        $Paylog = new Paylog();
        $mab['orderid'] = $orderid;
        $id = $Paylog->where($mab)->find();
        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $map['id'] = $id['mid'];
        $config = $Merchant->where($map)->find();
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
        $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();

        $options = array(
            'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
            'partnerid' => $agent['partnerid'], // 财付通商户身份标识
            'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
        );

        $weObj = new Wxobjopen($options);
        $appid = $users['authorizer_appid'];
        $mch_id = $agent['partnerid'];
        $out_trade_no = $orderid;
        $nonce_str = $weObj->generateNonceStr();
        $sub_mch_id = $config['sub_mch_id'];
        $sub_appid = $userwx['authorizer_appid'];
        $pay_xml = $weObj->createOrderXml($appid, $mch_id, $sub_appid, $sub_mch_id, $out_trade_no, $nonce_str);
        $payorder_xml = $weObj->getPayNum($pay_xml);
        $orderno = $payorder_xml['transaction_id'];
        $pay_zt = $payorder_xml['trade_state'];
        var_dump($payorder_xml);
    }

    public function index()
    {

        $msg = array();
        $request = request();
        if ($request->isPost()) {
            $msg = $request->post();
            $pay_zt = $msg['trade_status'];
            if ($pay_zt == "TRADE_SUCCESS") {

                $Paylog = new Paylog();
                $id = $Paylog->where(array('orderid' => $msg['out_trade_no']))->find();
                if ($id['tzzt'] == 0) {
                    trace( "支付宝支付异步通知-1：" . json_encode($id,256),'SysRunNotifyLog');
                    if ((int)$id['tzzt'] ==  0) {
                        trace( "支付宝支付异步通知-2：" . json_encode($id,256),'SysRunNotifyLog');
                        action('Alipay/order_query', array($msg['out_trade_no']));
                    } elseif ((int)$id['tzzt'] == 1) {
                        $su = 'success';
                        echo $su;
                        trace( "支付宝支付异步通知-3：" . json_encode($id,256),'SysRunNotifyLog');
                    }

                }

            }

        } else {
//            $this->redirect('show/index');
            $this->error('该页面不存在');
        }
    }

    public function getpay()
    {

        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        echo $user_agent;
        exit;
        $this->redirect('Wxpay/pay', $_GET);

        exit;
    }

    public function pay()
    {

        $Merchant = new Merchant();
        $request = request();

        $mchtd = $Merchant->where(array('id' => $request->param('id')))->field('wechat_way,ali_way')->find();
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($user_agent, 'AlipayClient')) {
            if ($mchtd['ali_way'] == 0) {
                $this->redirect('Alipay/pay', request()->param());
                exit;
            } elseif ($mchtd['ali_way'] == 1) {
                $this->redirect('Cmmbpay/alipay', request()->param());
                exit;
            } elseif ($mchtd['ali_way'] == 2) {
                $this->redirect('Alipay/pay', request()->param());
                exit;
            } elseif ($mchtd['ali_way'] == 10) {
                $this->redirect('Lftpay/alipay', request()->param());
                exit;
            } elseif ($mchtd['ali_way'] == 30) {
                $this->redirect('Huifupay/alipay', request()->param());
                exit;
            }

        }
        if (strpos($user_agent, 'MicroMessenger')) {
            if ($mchtd['wechat_way'] == 0) {
                $this->redirect('Wxpay/pay', request()->param());
                exit;
            } elseif ($mchtd['wechat_way'] == 1) {
                $this->redirect('Cmmbpay/pay', request()->param());
                exit;
            } elseif ($mchtd['wechat_way'] == 2) {
                $this->redirect('Wxnocardpay/pay', request()->param());
                exit;
            } elseif ($mchtd['wechat_way'] == 10) {
                $this->redirect('Lftpay/pay', request()->param());
                exit;
            } elseif ($mchtd['wechat_way'] == 30) {
                $this->redirect('Huifupay/wxpay', request()->param());
                exit;
            }
        }

    }

//支付广告位
    public function ad()
    {
        $request = request();
        if ($request->isAjax()) {
            $orderid = $request->post('orderid');
            $ggk = action('ad/adview', array($orderid));
            echo json_encode($ggk);


        }

    }

//支付刮刮卡
    public function getggk()
    {
        $request = request();
        if ($request->isAjax()) {
            $orderid = $request->post('orderid');
            $ggk = action('ggkview/ggk', array($orderid));
            return json($ggk);


        }

    }

    private function getorder($sh)
    {

        $order = "H" . $sh . "-" . date('YmdHis') . rand(10000, 99999);
        return $order;

    }

    //获取订单号

    public function getorder2()
    {
        $request = request();
        if ($request->isAjax()) {
            $sh = $request->post('id');
            $order = "H" . $sh . "-" . date('YmdHis') . rand(10000, 99999);
            echo $order;
        }
    }

    public function testprint()
    {
        $map['mid'] = 501;
        $Paylog = new Paylog();
        $id = $Paylog->where($map)->order('id desc')->find();
        $this->sendprint($id);


    }

    public function sendprint($id)
    {
        //$id=M('paylog')->where(array('orderid'=>"H503-2017011616111174693"))->find();
        $Print = new DevicePrint();
        $cfg = $Print->where(array('mid' => $id['mid']))->find();


        if ($cfg) {
            $payinfo = json_decode($id['payinfo'], true);

            $bank = $payinfo['bank_type'];
            $user = $cfg['username'];
            $ukey = $cfg['ukey'];
            $stime = time();
            $sig = sha1($user . $ukey . $stime);
            $sn = $cfg['sn'];


            $orderInfo = "<CB>" . getshmc($id['mid']) . "</CB><BR>";
            $orderInfo .= '--------------------------------<BR>';
            $orderInfo .= "订单号:<BR>" . $id['orderid'] . '<BR><BR>';
            $orderInfo .= "收单单号:<BR>" . $id['orderno'] . '<BR><BR>';
            $orderInfo .= '--------------------------------<BR>';

            $orderInfo .= "实收金额:<B>" . $id['price'] . '</B>元' . '<BR><BR>';
            $orderInfo .= "应收金额:" . $id['yf_price'] . '元' . '<BR><BR>';
            $orderInfo .= "折扣金额:" . $id['zk_price'] . '元' . '<BR><BR>';
            $orderInfo .= "消费时间:" . date("Y-m-d H:i:s", $id['add_time']) . '<BR><BR>';
            $orderInfo .= '--------------------------------<BR>';
            $orderInfo .= "技术支持:悟能科技(400-0372-203)" . '<BR><BR>';
            //$orderInfo .= ''.$_POST['riqi'].'<BR>';
            $this->wp_print($user, $stime, $sig, $sn, $orderInfo, 1);
        }

    }

    private function wp_print($user, $stime, $sig, $printer_sn, $orderInfo, $times)
    {
        $ip = 'api.feieyun.cn';        //接口IP或域名
        $port = 80;                    //接口IP端口
        $hostname = '/Api/Open/';    //接口路径
        $content = array(
            'user' => $user,
            'stime' => $stime,
            'sig' => $sig,
            'apiname' => 'Open_printMsg',

            'sn' => $printer_sn,
            'content' => $orderInfo,
            'times' => $times//打印次数
        );
        $image = new HttpClient($ip, $port);
        if (!$image->post($hostname, $content)) {
            echo 'error';
        } else {
            header("Content-type: text/html; charset=utf-8");
            $s = $image->getContent();

        }

    }

    public function cashier()
    {
        $request = request();
        Session::set('openid', null);
        $System = new System();
        $config = $System->where(array('id' => 1))->find();
        $WxOpen = new WxOpen();
        $users = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],

        );
        $weObj = new Wxobjopen($options);
        $openid = session('openid');

        if (strlen($openid) <= 10) {
            $info = $weObj->getOpenoauthAccessToken();
            if (!$info) {
                $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("Index/cashier", array('id' => $request->get('id')));
                $url = $weObj->getopenOauthRedirect($callback, '', 'snsapi_base');

                header("Location: $url");
                exit();
            } else {

                $openid = $info['openid'];

            }
        }
        $userinfo = $weObj->getUserInfo($openid);
        //$userinfo = json_encode($userinfo);
        if ($userinfo['subscribe'] == 0) {
            $this->error('请先关注公众号');

        }

        // var_dump($userinfo);
//    $me['openid']=$openid;
//    $me=I('get.id');
        $me['mid'] = $request->get('machid');
        $me['openid'] = $openid;
        $Cashier = new MerchantCashier();
        $cx = $Cashier->where($me)->count();

        if ($cx == 0) {
            $code = rand(pow(1, 5), pow(10, 5));
            $data['openid'] = $openid;
            $data['code'] = $code;
            $data['addtime'] = time();
            $data['mid'] = $request->get('machid');
            $Bdsy = new Bdsy();
            $add = $Bdsy->save($data);
            if ($add) {
                $this->assign('code', $code);

            }
            $ma4['id'] = $request->get('machid');
            $Merchant = new Merchant();
            $machname = $Merchant->where($ma4)->value('merchant');
            $this->assign('machname', $machname);
            $this->display();
        } else {
            $this->error('您已绑定过该门店，请勿重复绑定');
        }
    }

    //删除收银员
    public function getsy()
    {
        $map['id'] = 1;
        $Merchant = new Merchant();
        $config = $Merchant->where($map)->find();
        $options = array(
            //'token' => $config ["token"], // 填写你设定的key
            //'encodingaeskey' => $config ["encodingaeskey"], // 填写加密用的EncodingAESKey
            'appid' => $config['appid'], // 填写高级调用功能的app id
            'appsecret' => $config['appsecret'], // 填写高级调用功能的密钥
            'partnerid' => $config['partnerid'], // 财付通商户身份标识
            'partnerkey' => $config['partnerkey'], // 财付通商户权限密钥Key
            //'paysignkey' => $config ["paysignkey"]  // 商户签名密钥Key
        );
        $weObj = new Wxobjopen ($options);
        $access_token = $weObj->checkopenAuth();
        $Cashier = new MerchantCashier();
        $cashier = $Cashier->field('id,openid')->select();
        foreach ($cashier as $k => $v) {
            $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $access_token . "&openid=" . $v['openid'] . "&lang=zh_CN ";
            $res = json_decode($this->http_request($url), true);

            if ($res['subscribe'] == 0) {
                $s[] = $v['id'];
                $Cashier = new MerchantCashier();
                $del = $Cashier->where(array('id' => $v['id']))->delete();


            }
        }
        var_dump($s);
    }

    public function http_request($url, $data = array())
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
// 我们在POST数据哦！
        curl_setopt($ch, CURLOPT_POST, 1);
// 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

}
